package com.carrental.api.company.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.carrental.api.company.domain.CompanyInfo;
import com.carrental.api.company.domain.DingQueryParam;
import com.carrental.api.company.domain.DingResponseData;
import com.carrental.common.core.controller.BaseController;
import com.carrental.common.exception.OperationException;
import com.carrental.common.response.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LiangYi
 * @since 2022/8/6 18:14
 */
@RequestMapping("/company")
@RestController
@Slf4j
public class CompanyController extends BaseController {

    @PostMapping()
    public void queryCompany(@RequestBody List<String> companyName, HttpServletResponse response) throws IOException {
        if (companyName.isEmpty()) {
            throw new OperationException("请输入商企名称");
        }
        String dingdingApi = "https://holmes.taobao.com/web/corp/customer/searchWithSummary";
        HashMap<String, Object> paramMap = new HashMap<>(8);
        List<CompanyInfo> companyInfoList = new ArrayList<>();
        for (String name : companyName) {
            DingQueryParam queryParam = new DingQueryParam();
            queryParam.setKeyword(name);
            Map<String, Object> map = new HashMap<>(8);
            String result = HttpRequest.post(dingdingApi)
                .header("orgin", "https://www.dingtalk.com")
                .cookie("cna=iNuTGtahjHQCATspd+H5Jthk; t=055b729acc9d624b3ba684ca98956cb1; x5sec=7b22617365727665723b32223a226138326436656364386235633335316437643330323834343266393436323537434b4c59755a6347454c6a33306f4b38314965524a4443527a7247672f2f2f2f2f2f38424f674a724d554144227d; isg=BFZW_G2LKM9wPRyZNxHFhTPDpwxY95oxB4a9HMC_EDnUg_cdKIezQWY6Gh9vYJJJ")
                .body(JSON.toJSONString(queryParam))
                .execute().body();

            DingResponseData responseData = JSON.parseObject(result, DingResponseData.class);
            CompanyInfo companyInfo = new CompanyInfo();
            if (responseData.getData().getTotal() > 0) {
                companyInfo = responseData.getData().getData().get(0);
                //提取电话列表
                if (companyInfo.getTelephoneDetailLists() != null) {
                    companyInfo.setPhones(StringUtils.strip(companyInfo.getTelephoneDetailLists().stream().map(CompanyInfo.TelephoneData::getTelephone).collect(Collectors.toList()).toString(),"[]"));
                }else{
                    companyInfo.setPhones("无");
                }
            }
            companyInfoList.add(companyInfo);
            log.info("查询：{} 信息完成，{}详细信息", name, companyInfo.getCompanyName() == null ? "无" : "有");
        }
        //return CommonResult.success(new CompanyInfo());
        exportCompanyInfo(response, companyInfoList);
    }

    public void exportCompanyInfo(HttpServletResponse response, List<CompanyInfo> companyInfoList) throws IOException {
        // 这里需要注意 在使用ExcelProperty注解的使用，如果想不空列则需要加入order字段，而不是index,order会忽略空列，然后继续往后，而index，不会忽略空列，在第几列就是第几列。

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("商户数据", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            Set<String> includeColumnFiledNames = new HashSet<String>();
            includeColumnFiledNames.add("companyName");
            //includeColumnFiledNames.add("bizStatus");
            includeColumnFiledNames.add("legalPerson");
            includeColumnFiledNames.add("phones");
            EasyExcel.write(response.getOutputStream(), CompanyInfo.class).autoCloseStream(Boolean.FALSE).sheet("")
                .includeColumnFiledNames(includeColumnFiledNames)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(companyInfoList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
}
